package com.hq.fxh.No0_ChengQu.Activity;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hq.fxh.CustomerView.ShareDialogUtils;
import com.hq.fxh.CustomerView.countview.EmptyView;
import com.hq.fxh.HttpApi.ArticleServiceImpl;
import com.hq.fxh.HttpApi.UserServiceImpl;
import com.hq.fxh.Modle.ShareArticleRes;
import com.hq.fxh.No0_ChengQu.Fragment.AdTemplateV2Fragment;
import com.hq.fxh.No5_User.MyModle.Activity.item.ToastUtils;
import com.hq.fxh.No5_User.MyModle.AdBannerInfo;
import com.hq.fxh.No5_User.MyModle.AdEditorActivity;
import com.hq.fxh.No5_User.MyModle.AdInfo;
import com.hq.fxh.No5_User.MyModle.Config;
import com.hq.fxh.No5_User.MyModle.Model.CommonRes;
import com.hq.fxh.No5_User.MyModle.Model.GetAdvertByUidRes;
import com.hq.fxh.No5_User.MyModle.Model.ShareInfo;
import com.hq.fxh.R;
import com.hq.fxh.Utils.IntentUtils;
import com.hq.fxh.Utils.SharedPreferenceUtils;

import java.util.List;

import cn.jiguang.analytics.android.api.JAnalyticsInterface;
import rx.Subscriber;

/**
 * @author 大圣
 * @ClassName News_AddAD_DetailActivity
 * @Description : 文章加入广告分享
 * @Created 16/5/18
 * @Email qwqe601660957@163.com
 */
public class News_AddAD_DetailActivity extends BaseActivity {
    private LinearLayout llShare;
    private TextView tvRight;
    private EmptyView emptyView;
    private LinearLayout rlContent;
    private WebView webView;
    /**
     * 头部广告编辑
     */
    private LinearLayout topfill;
    /**
     * 底部广告编辑
     */
    private RelativeLayout footfill;
    /**
     * 头部广告
     */
    private AdTemplateV2Fragment headFragment;
    /**
     * 底部广告
     */
    private AdTemplateV2Fragment footV2Fragment;


//    private Article article;
    /**
     * 模板广告信息
     */
    private AdInfo adInfo;
    private int editorWay;
    private long merchantArticleId;
    private String url;
    /**
     * 底部广告当前选项
     */
    private int currentPosition;
    /**
     * 顶部广告当前选项
     */
    private int adHeadPosition;
    /**
     * 顶部文章模板ID
     */
    private long TopMerchantTempletId;
    /**
     * 底部s文章模板ID
     */
    private long MerchantTempletId;
    private int articleId;
    private ShareInfo shareInfo;
    private CheckBox checkBox;
    private int uid;
    private GetAdvertByUidRes.DataBean adData;
    private ShareArticleRes.DataBean shareData;
    private int sharePosition;
    private int returnSuspend;//1 广告悬浮，0 广告不悬浮
    private boolean isShowAgreement = false;
    private ProgressDialog progressDialog;
    private LinearLayout no_suspend;
    private View layoutAdBack;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_article_detail;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        headFragment = new AdTemplateV2Fragment();
        footV2Fragment = new AdTemplateV2Fragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flHead, headFragment);
        fragmentTransaction.replace(R.id.flFoot, footV2Fragment);
        fragmentTransaction.commitAllowingStateLoss();
        getAdTemplateListInfo();
    }

    @Override
    protected void initView() {
        no_suspend = (LinearLayout) findViewById(R.id.ll_no_suspend);
        llShare = (LinearLayout) findViewById(R.id.llShare);
        tvRight = (TextView) findViewById(R.id.tvRight);
        rlContent = (LinearLayout) findViewById(R.id.rlContent);
        emptyView = (EmptyView) findViewById(R.id.emptyView);
        topfill = (LinearLayout) findViewById(R.id.Topfill);
        layoutAdBack = findViewById(R.id.layout_Ad_Back);

        footfill = (RelativeLayout) findViewById(R.id.Footfill);
        webView = (WebView) findViewById(R.id.webView);
        checkBox = (CheckBox) findViewById(R.id.checkBox);
    }

    @Override
    protected void initData() {
        returnSuspend = SharedPreferenceUtils.getIsflout(News_AddAD_DetailActivity.this);
        uid = SharedPreferenceUtils.getMemberId(News_AddAD_DetailActivity.this);
        shareInfo = new ShareInfo();
        setTitle("编辑广告");
        emptyView.bindView(rlContent);
      /*  emptyView.buttonClick(this, Config.TRY_AGAIN);*/

        headFragment = new AdTemplateV2Fragment();
        footV2Fragment = new AdTemplateV2Fragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.flHead, headFragment);
        fragmentTransaction.replace(R.id.flFoot, footV2Fragment);
        fragmentTransaction.commit();

        registerListener();
        fillWebView();
        isShowAgreement = SharedPreferenceUtils.getIsShowAgreement(News_AddAD_DetailActivity.this);
        if (isShowAgreement == false) {
//            agreementIsShow();
        }

        returnSuspend = SharedPreferenceUtils.getIsflout(News_AddAD_DetailActivity.this);
        if (returnSuspend == 0) {
            checkBox.setChecked(false);
        } else if (returnSuspend == 1) {
            checkBox.setChecked(true);
        }

        layoutAdBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void agreementIsShow() {
        new AlertDialog.Builder(News_AddAD_DetailActivity.this).setTitle("系统提示")//设置对话框标题
                .setMessage("严禁上传包括 “反动、暴力、色情、违法及侵权内容” 的图文信息。一经发现，永久封锁帐号。")//设置显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//添加确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {//添加返回按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {//响应事件
            }
        }).show();//在按键响应事件中显示此对话框
        isShowAgreement = true;
        SharedPreferenceUtils.setIsShowAgreement(isShowAgreement, News_AddAD_DetailActivity.this);
    }

    private void fillWebView() {
        getAdTemplateListInfo();

        Bundle bundle = this.getIntent().getExtras();
        if (bundle != null) {
            url = bundle.getString("NewsUrl");
            WebSettings settings = webView.getSettings();
            settings.setJavaScriptEnabled(true);//启用支持javascript
            settings.setBlockNetworkImage(false);//是否显示网络图像
            settings.setBuiltInZoomControls(true);//设置是否支持缩放
            settings.setDomStorageEnabled(true);/* 大部分网页需要自己保存一些数据,这个时候就的设置下面这个属性 */
            settings.setUseWideViewPort(true);/* 设置为使用webview推荐的窗口 */
            settings.setLoadWithOverviewMode(true);/* 设置网页自适应屏幕大小 ---这个属性应该是跟上面一个属性一起用 */
            webView.setHorizontalScrollBarEnabled(false);/* 设置显示水平滚动条,就是网页右边的滚动条.我这里设置的不显示 */
            webView.loadUrl(url);

            //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
       /*     webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                    view.loadUrl(url);
                    return true;
                }
            });*/

        }
    }

    public void registerListener() {
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (returnSuspend == 0) {
                    ToastUtils.show(News_AddAD_DetailActivity.this, "广告悬浮");
                    returnSuspend = 1;
                    checkBox.setChecked(true);
                } else if (returnSuspend == 1) {
                    ToastUtils.show(News_AddAD_DetailActivity.this, "广告不悬浮");
                    checkBox.setChecked(false);
                    returnSuspend = 0;
                }
                SharedPreferenceUtils.setIsflout(News_AddAD_DetailActivity.this, returnSuspend);
            }
        });

        llShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = ProgressDialog.show(News_AddAD_DetailActivity.this, "", "加载中，请稍后……");
                progressDialog.setCancelable(true);//设置进度条是否可以按退回键取消
                progressDialog.setCanceledOnTouchOutside(true);
                pasterNewsUrl(url);
            }
        });

        topfill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int isActive = SharedPreferenceUtils.getIs_active(News_AddAD_DetailActivity.this);
                if (isActive == 0) {
                    ToastUtils.show(News_AddAD_DetailActivity.this, "请先购买激活产品来解锁顶部广告模板");
                } else {
                    toAdEditorHeadActivity();
                }
            }
        });
        footfill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toAdEditorFootActivity();
            }
        });
    }

    private void toAdEditorFootActivity() {
        /** 底部广告编辑 */
        Bundle pBundle = new Bundle();
        pBundle.putInt(Config.WAY, 0);
        pBundle.putInt(Config.POSITION, footV2Fragment.getCurrentPosition());
        pBundle.putInt(Config.AD_HEAD_POSITION, headFragment.getCurrentPosition());
        pBundle.putLong(Config.CUR_TOP_ID, headFragment.getCurMerId());
        pBundle.putLong(Config.CUR_FOOT_ID, footV2Fragment.getCurMerId());
        pBundle.putBoolean("isShowTiePianAd", false);
        IntentUtils.openActivityForResult(this, AdEditorActivity.class, Config.RequestCode.AD_TEMPLATE_ADD, pBundle);
    }

    private void toAdEditorHeadActivity() {
        /** 头部广告编辑 */
        Bundle bundle = new Bundle();
        bundle.putInt(Config.WAY, 1);
        bundle.putInt(Config.POSITION, footV2Fragment.getCurrentPosition());
        bundle.putInt(Config.AD_HEAD_POSITION, headFragment.getCurrentPosition());
        bundle.putLong(Config.CUR_TOP_ID, headFragment.getCurMerId());
        bundle.putLong(Config.CUR_FOOT_ID, footV2Fragment.getCurMerId());
        bundle.putBoolean("isShowTiePianAd", false);
        IntentUtils.openActivityForResult(this, AdEditorActivity.class, Config.RequestCode.AD_TEMPLATE_ADD, bundle);
    }

    public void pasterNewsUrl(String url) {
        /** 用户粘贴文章文章操作 */
        ArticleServiceImpl.pasterNewsUrl(url, new Subscriber<CommonRes>() {


            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                ToastUtils.show(News_AddAD_DetailActivity.this, e.toString());
            }

            @Override
            public void onNext(CommonRes data) {
                if (data != null && data.getCode() == 0) {
                    String key = data.getData().toString();
                    shareArticle(key);
                } else {
                    ToastUtils.show(News_AddAD_DetailActivity.this, data.getMsg());
                }
            }
        });
    }


    public void shareArticle(String key) {
        ArticleServiceImpl.shareArticle(uid + "", key, returnSuspend, new Subscriber<ShareArticleRes>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(ShareArticleRes data) {
                if (data != null && data.getCode() == 0) {
                    shareData = data.getData();
                    articleId = shareData.getArticle_member_id();
                    progressDialog.dismiss();

                } else {
                    progressDialog.dismiss();
                    ToastUtils.show(News_AddAD_DetailActivity.this, data.getMsg());
                }
            }


        });
    }

    public void shareA() {
        ShareDialogUtils.showShareView(News_AddAD_DetailActivity.this, webView, new ShareDialogUtils.SharePopCallBack() {
            @Override
            public void Call(AdapterView<?> adapterView, View view, int i, long l) {
                sharePosition = i;
                ShareDialogUtils.dismiss();
                if (sharePosition == 5) {
                    /** 复制链接操作 */
                    ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    clipboardManager.setText(shareData.getShare_url());
                    ToastUtils.show(News_AddAD_DetailActivity.this, "已复制");
                } else {
                          /*      SHARE_MEDIA share_media = UmengManager.getInstance(News_AddAD_DetailActivity.this).getShareMedia(ShareDialogUtils.titles[sharePosition]);
                                shareInfo.setTitle(shareData.getTitle());
                                shareInfo.setImgUrl(shareData.getTitle_pic_url());
                                if (TextUtils.isEmpty(shareData.getSummary())) {
                                    shareInfo.setText(shareData.getTitle());
                                } else {
                                    shareInfo.setText(shareData.getSummary());
                                }
                                shareInfo.setUrl(shareData.getShare_url());
                                shareInfo.setArticleId(shareData.getArticle_member_id());
                                UmengManager.getInstance(News_AddAD_DetailActivity.this).share(News_AddAD_DetailActivity.this, shareInfo, share_media, null);*/
                }
            }
        });
    }


    /**
     * 获取广告模板信息
     */
    public void getAdTemplateListInfo() {

        UserServiceImpl.getAdTemp(uid + "", new Subscriber<GetAdvertByUidRes>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(GetAdvertByUidRes data) {
                if (data != null && data.getCode() == 0) {
                    adData = data.getData();
                    headFragment.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle pBundle = new Bundle();
                            pBundle.putInt(Config.WAY, 1);
                            pBundle.putInt(Config.POSITION, footV2Fragment.getCurrentPosition());
                            pBundle.putInt(Config.AD_HEAD_POSITION, headFragment.getCurrentPosition());
                            pBundle.putLong(Config.CUR_TOP_ID, headFragment.getCurMerId());
                            pBundle.putLong(Config.CUR_FOOT_ID, footV2Fragment.getCurMerId());
                            pBundle.putBoolean("isShowTiePianAd", false);
                            IntentUtils.openActivityForResult(News_AddAD_DetailActivity.this, AdEditorActivity.class, Config.RequestCode.AD_TEMPLATE_ADD, pBundle);
                        }
                    });
                    List<AdBannerInfo> topList = adData.getTop();
                    boolean topAllClose = true;
                    //type var : arr
                    for (AdBannerInfo topDate : topList) {
                        if (topDate.getIs_carousel() == 1) {
                            topAllClose = false;
                        }
                    }
                    if (adData.getTop().size() <= 0 || topAllClose) {
                        topfill.setVisibility(View.VISIBLE);
                    } else {
                        topfill.setVisibility(View.GONE);
                    }
                    headFragment.showAdInfo(adData.getTop(), adHeadPosition);

                    footV2Fragment.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle pBundle = new Bundle();
                            pBundle.putInt(Config.WAY, 0);
                            pBundle.putInt(Config.POSITION, footV2Fragment.getCurrentPosition());
                            pBundle.putInt(Config.AD_HEAD_POSITION, headFragment.getCurrentPosition());
                            pBundle.putLong(Config.CUR_TOP_ID, headFragment.getCurMerId());
                            pBundle.putLong(Config.CUR_FOOT_ID, footV2Fragment.getCurMerId());
                            pBundle.putBoolean("isShowTiePianAd", false);
                            IntentUtils.openActivityForResult(News_AddAD_DetailActivity.this, AdEditorActivity.class, Config.RequestCode.AD_TEMPLATE_ADD, pBundle);
                        }
                    });
                    List<AdBannerInfo> bottomList = adData.getBottom();
                    boolean bottomAllClose = true;
                    //type var : arr
                    for (AdBannerInfo bottomDate : bottomList) {
                        if (bottomDate.getIs_carousel() == 1) {
                            bottomAllClose = false;
                        }
                    }
                    if (adData.getBottom().size() <= 0 || bottomAllClose) {
                        footfill.setVisibility(View.VISIBLE);
                    } else {
                        footfill.setVisibility(View.GONE);
                    }
                    if (adData.getBottom() != null && adData.getBottom().size() > 0 && adData.getBottom().get(0).getAdvert_type_id() == Config.AdTypeCode.AD_BIG_BANNER && adData.getBottom().get(0).getIs_carousel() == 1) {//大图通栏广告只在第一位（有大图通栏广告切打开）
                        no_suspend.setVisibility(View.GONE);
                    } else {
                        no_suspend.setVisibility(View.VISIBLE);
                    }
                    footV2Fragment.showAdInfo(adData.getBottom(), currentPosition);
                } else {
                    ToastUtils.show(News_AddAD_DetailActivity.this, data.getMsg());
                }
            }


        });
    }


    /**
     * 分享成功后调用
     */
    public void afterShareSuccess(long merchantArticleId, int channelTypeId) {

   /*     if (CommonUtils.isLogin()) {
            ShareSucceedReq req = new ShareSucceedReq();
            req.setMerchantId(CommonUtils.getUserId());
            req.setChannelTypeId(channelTypeId);
            req.setMerchantArticleId(merchantArticleId);
            req.setIdentity(CommonUtils.seetIdentity(this));
        }
*/
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
/*
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
*/
        if (resultCode == Config.ResultCode.AD_TEMPLATE_ADD) {
            if (requestCode == Config.RequestCode.AD_TEMPLATE_ADD) {
                if (data != null) {
                    currentPosition = data.getExtras().getInt(Config.POSITION);
                    adHeadPosition = data.getExtras().getInt(Config.AD_HEAD_POSITION);
                    TopMerchantTempletId = data.getExtras().getLong(Config.CUR_TOP_ID);
                    MerchantTempletId = data.getExtras().getLong(Config.CUR_FOOT_ID);
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
        JAnalyticsInterface.onPageStart(this, "编辑广告");
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
        JAnalyticsInterface.onPageEnd(this, "编辑广告");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
